//
//  XJComposeView.swift
//  新浪微博
//
//  Created by 徐绩 on 16/4/25.
//  Copyright © 2016年 ayumi. All rights reserved.
//

import UIKit
import pop

class XJComposeView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /**
     按钮数组
     */
    lazy var btnArr: [XJComposeBtn] = []
    
    /// 模型数组
    lazy var modelArray:[XJComposeBtnInfo] = {
    
        return self.btnInfos()
    }()
    
    /**
     点击按钮跳转的控制器
     */
    var target: UIViewController?
    
    
    private func setupUI() {
    
        frame = UIScreen.mainScreen().bounds

        //添加磨砂效果
        let image = UIImage.getScreenShot().applyLightEffect()
        let imageView = UIImageView(image: image)
        addSubview(imageView)
        
        //添加标语图片
        addSubview(sloganImage)
        sloganImage.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.top.equalTo(150)
        }
        
        addChildBtns()
        btnInfos()
    
    }
    /**
     添加按钮
     */
    private func addChildBtns(){
        
        let btnW: CGFloat = 80
        let btnH: CGFloat = 110
        let margin: CGFloat = (SCREENW - 3 * btnW) / 4
        
        let array = btnInfos()
        for (i,value) in array.enumerate() {
            
            //添加按钮到界面
            let btn = XJComposeBtn(textColor: UIColor.darkGrayColor(), fontSize: 14)
            btn.tag = i
            
            //按钮点击事件
            btn.addTarget(self, action: "didClickBtn:", forControlEvents: .TouchUpInside)
            btn.setTitle(value.title, forState: .Normal)
            btn.setImage(UIImage(named: value.icon!), forState: .Normal)
            btn.frame.size = CGSizeMake(btnW, btnH)
            addSubview(btn)
            //按钮添加到数组
            self.btnArr.append(btn)
            
            //调整位置
            let col = i % 3
            let row = i / 3
            
            btn.frame.origin.x = margin * CGFloat(col + 1) + CGFloat(col) * btnW
            btn.frame.origin.y = 10 * CGFloat(row) + CGFloat(row) * btnH + SCREENH
        }
        
    }
    
    /**
     供外界调用弹出控制器
     */
    func show(target: UIViewController?){
    
        target?.view.addSubview(self)
        self.target = target
    }
    
    /**
     监听按钮点击事件
     */
   @objc private func didClickBtn(button: UIButton) {
    
    UIView.animateWithDuration(0.25, animations: { () -> Void in
        
        for value in self.btnArr {
        
            value.alpha = 0.01
            if value == button{
            
                value.transform = CGAffineTransformMakeScale(2, 2)
            }else{
                value.transform = CGAffineTransformMakeScale(0.01, 0.01)
            
            }
        }
        
        }) { (_) -> Void in
            
            //弹出控制器
            let model = self.modelArray[button.tag]
            let type = NSClassFromString(model.className!)! as! UIViewController.Type
            
            let vc = type.init()
            // let vc = XJComposeViewController()
            
            self.target?.presentViewController(UINavigationController(rootViewController: vc), animated: true, completion: { () -> Void in
                self.removeFromSuperview()
            })
        }
    }
    
    /**
     读取plist文件,字典转模型
     */
    private func btnInfos() -> [XJComposeBtnInfo] {
        
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!
        let arr = NSArray(contentsOfFile: path)!
        
        var tempArr: [XJComposeBtnInfo] = []
        for values in arr {
            
            let btnInfo = XJComposeBtnInfo(dict: values as! [String : AnyObject])
            tempArr.append(btnInfo)
        }
        return tempArr
    }
    
    /**
     将要添加到父控件上时调用
     */
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        super.willMoveToSuperview(newSuperview)
        
        //执行动画
        for (index, value) in btnArr.enumerate(){
        
            animation(value, index: index, isUp: true)
        }
    }
    
    
    /**
     btn动画修改btn位置
    */
    func animation(value: UIView, index: Int, isUp: Bool) {
    
        //动画对象
        let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        
        //结束位置向上y值变小,不是向上y值变大
        anim.toValue = NSValue(CGPoint: CGPoint(x: value.center.x, y: value.center.y + (isUp ? -370 : 370)))
        
        //属性
        anim.springSpeed = 10
        anim.springBounciness = 8
        
        anim.beginTime = Double(index) * 0.025 + CACurrentMediaTime()
        
        value.pop_addAnimation(anim, forKey: nil)
    }
    
    /**
     移除View
     */
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        super.touchesBegan(touches, withEvent: event)
        
        for(index, value) in btnArr.reverse().enumerate() {
            animation(value, index: index, isUp: false)
        }
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.4 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            
            self.removeFromSuperview()
        }
    }
    
        
   
    // MARK: -  懒加载控件

    //标语图片
    private lazy var sloganImage = UIImageView(image: UIImage(named: "compose_slogan"))
    

}
